package com.claimSettlement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.claimSettlement.mapper.RecognizeeMapper;
import com.claimSettlement.pojo.Recognizee;
import com.claimSettlement.service.RecognizeeService;
import com.claimSettlement.utils.JsonUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 被保人信息业务层
 * 曹文韬 -- 2021-05-19
 */
@Service
public class RecognizeeServiceImpl implements RecognizeeService {
    @Resource
    private RecognizeeMapper recognizeeMapper;

    @Resource
    RedisTemplate<String,Object> redisTemplate;


    public List<Recognizee> getRecognizeeAll() {
        redisTemplate.delete("recogList");
        List<Recognizee> list = null;
        if(redisTemplate.hasKey("recogList")){
            list = JsonUtils.jsonToList(redisTemplate.opsForHash().values("recogList").toString(),Recognizee.class);
        }else{
            QueryWrapper<Recognizee> queryWrapper = new QueryWrapper();
            queryWrapper.orderByAsc("recognizeeId");
            list = recognizeeMapper.selectList(queryWrapper);
            Map<String,String> map = new HashMap();
            for (Recognizee recognizee: list) {
                map.put(String.valueOf(recognizee.getRecognizeeId()),JsonUtils.objectToJson(recognizee));
            }
            redisTemplate.opsForHash().putAll("recogList",map);
        }

        return list;
    }

    public List<Recognizee> getRecognizeeByNameOrCredentialsId(String name, String credentialsId) {
        return recognizeeMapper.getRecognizeeByNameOrCredentialsId(name, credentialsId);
    }

    public Recognizee getRecognizeeById(int recognizeeId) {
        return recognizeeMapper.selectById(recognizeeId);
    }

    public int insRecognizee(Recognizee recognizee) {
        int count = recognizeeMapper.insert(recognizee);
        if(count > 0){
            redisTemplate.opsForHash().put("recogList",recognizee.getRecognizeeId(),JsonUtils.objectToJson(recognizee));
        }
        return count;
    }

    public int updRecognizee(Recognizee recognizee) {
        int count = recognizeeMapper.updateById(recognizee);
        if(count > 0){
            redisTemplate.opsForHash().put("recogList",recognizee.getRecognizeeId(),JsonUtils.objectToJson(recognizee));
        }
        return count;
    }

    public int delRecognizee(int recognizeeId) {
        int count = recognizeeMapper.deleteById(recognizeeId);
        if(count > 0){
            redisTemplate.delete("recogList");
        }
        return count;
    }

    public List<Recognizee> getRecognizeePid() {
        return recognizeeMapper.getRecognizeePid();
    }
}
